package com.king.gkrpc.server;

import com.king.gkrpc.Request;
import com.king.gkrpc.ServiceDescript;
import com.king.gkrpc.common.utils.ReflectionUtils;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 管理rpc暴露的服务
 */
@Slf4j
public class ServiceManager {
    /**
     * 这边使用ServiceDescript 作为map的key，因为是使用equals判断，故需要对ServiceDescript的equals进行
     */
    private Map<ServiceDescript,ServiceInstance> services;

    public ServiceManager(){
        this.services = new ConcurrentHashMap<ServiceDescript, ServiceInstance>();
    }

    public <T> void register(Class<T> interfaceClass,T bean){
        Method[] methods = ReflectionUtils.getPublicMethods(interfaceClass);
        for(Method method :methods){
            ServiceInstance sis = new ServiceInstance(bean,method);
            ServiceDescript sdp = ServiceDescript.from(interfaceClass,method);

            services.put(sdp,sis);

            log.info("register service : {} {}",sdp.getClazz(),sdp.getMethod());
        }
    }

    public ServiceInstance lookup(Request request){
        ServiceDescript sdp = request.getService();
        return services.get(sdp);
    }
}
